﻿using IPlugins.Events;
using IPlugins;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using IPlugin.Events;

namespace PluginHost
{
    public class PluginHost : IPluginHost
    {
        public readonly Dictionary<string, Delegate> Functions = new Dictionary<string, Delegate>();
        public readonly List<IPlugins.IPlugin> Plugins = new List<IPlugins.IPlugin>();
        public List<PluginConfig> PluginConfigs = new List<PluginConfig>();

        public event EventHandler<PluginMenuEvent> MenuAdding;
        public event EventHandler<PluginMessageEvent> MessageShowing;
        public event EventHandler<PluginConfigEvent> ConfigRequested;

        public Form MainForm { get; set; }

        #region IPluginHost 实现

        public void RegisterFunction(string name, Delegate function)
        {
            if (Functions.ContainsKey(name))
                Functions[name] = function;
            else
                Functions.Add(name, function);
        }

        public object CallFunction(string name, params object[] args)
        {
            if (Functions.TryGetValue(name, out var func))
                return func.DynamicInvoke(args);

            throw new InvalidOperationException($"Function '{name}' not found");
        }

        public Form CreateSandboxForm()
        {
            return new Form
            {
                StartPosition = FormStartPosition.CenterParent,
                ShowInTaskbar = false,
                TopLevel = false,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                MaximizeBox = false,
                MinimizeBox = false
            };
        }

        public void AddPluginMenu(ToolStripMenuItem menuItem)
        {
            MenuAdding?.Invoke(this, new PluginMenuEvent(menuItem));
        }

        public void ShowMessage(string message, string title = "Message")
        {
            MessageShowing?.Invoke(this, new PluginMessageEvent(message, title));
        }

        public void ShowPluginConfig(string pluginName, UserControl configControl)
        {
            ConfigRequested?.Invoke(this, new PluginConfigEvent(pluginName, configControl));
        }
        #endregion

        public void InitializePluginSystem()
        {
            new PluginFunc(this).InitializePluginSystem();
        }

        

    }

}
